﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebUI.Models;
using DomainModel;
using Utils;
using System.Web.Mvc;

namespace WebUI.Utils
{
    public class ViewModelUtils
    {
        //check if someone contact one ind recently (7 days )
        public static Boolean IsSentRecently(EmailLog emailLog)
        {
            return emailLog != null && emailLog.EmailLogID > 0 && (emailLog.CreateDate.AddDays(7) > DateTime.Now);
        }

        public static Boolean IsAdmin()
        {
            UserIdentityModel identity = ViewModelUtils.CreateUserIdentityModel(false);
            if (identity.IsLoggedIn)
            {
                Login login = DataUtils.GetLoginByID(identity.LoginID);
                return login != null && login.IsAdmin;
            }
            else
            {
                return false;
            }
        }

        public static UserIdentityModel CreateUserIdentityModel(Boolean bLogOnPartialView = true)
        {
            return new UserIdentityModel(bLogOnPartialView);
        }

        public static IEnumerable<SelectListItem> GetSelectListItems(List<JobExp> jobExpList, int selectedJobExpID)
        {
            if (jobExpList == null || jobExpList.Count == 0)
            {
                return null;
            }
            if (selectedJobExpID <= 0)
            {
                selectedJobExpID = jobExpList[0].JobExpID;
            }
            return jobExpList.Select(x => new SelectListItem { Value = x.JobExpID.ToString(), Text = x.DName, Selected = x.JobExpID == selectedJobExpID });

        }

        public static IEnumerable<SelectListItem> GetSelectListItems(List<JobType> jobTypeList, int selectedJobTypeID)
        {
            if (jobTypeList == null || jobTypeList.Count == 0)
            {
                return null;
            }
            if (selectedJobTypeID <= 0)
            {
                selectedJobTypeID = jobTypeList[0].JobTypeID;
            }
            return jobTypeList.Select(x => new SelectListItem { Value = x.JobTypeID.ToString(), Text = x.DName, Selected = x.JobTypeID == selectedJobTypeID });

        }

        public static IEnumerable<SelectListItem> GetSelectListItems(List<CoType> coTypeList, int selectedCoTypeID)
        {
            if (coTypeList == null || coTypeList.Count == 0)
            {
                return null;
            }
            if (selectedCoTypeID <= 0)
            {
                selectedCoTypeID = coTypeList[0].CoTypeID;
            }
            return coTypeList.Select(x => new SelectListItem { Value = x.CoTypeID.ToString(), Text = x.DName, Selected = x.CoTypeID == selectedCoTypeID });

        }

        public static IEnumerable<SelectListItem> GetSelectListItems(List<JobPackage> jobPackageList, int selectedJobPackageID)
        {
            if (jobPackageList == null || jobPackageList.Count == 0)
            {
                return null;
            }
            if (selectedJobPackageID <= 0)
            {
                selectedJobPackageID = jobPackageList[0].JobPackageID;
            }
            return jobPackageList.Select(x => new SelectListItem { Value = x.JobPackageID.ToString(), Text = x.DName, Selected = x.JobPackageID == selectedJobPackageID });
        }

        public static string GetJobGUIDFromToken(string jobToken)
        {
            string jobGUID = string.Empty;
            if (!string.IsNullOrEmpty(jobToken))
            {
                try
                {
                    int index = jobToken.LastIndexOf("-");
                    jobGUID = jobToken.Substring(0, index);

                }
                catch { }
            }
            return jobGUID;
        }

        public static int GetJobIDFromToken(string jobToken)
        {
            int jobID = 0;

            if (!string.IsNullOrEmpty(jobToken))
            {
                try
                {
                    int index = jobToken.LastIndexOf("-");
                    jobID = Convert.ToInt32(jobToken.Substring(index + 1));
                }
                catch { }
            }
            return jobID;
        }

        public static string GetUploadErrorMessage(UploadResultEnum uploadResultEnum)
        {
            if (uploadResultEnum == UploadResultEnum.InternalError)
            {
                return "Internal error occurs, please try it again";
            }
            else if (uploadResultEnum == UploadResultEnum.FileSizeTooBig)
            {
                return "The filesize is too big";
            }
            else if (uploadResultEnum == UploadResultEnum.ImageWidthInvalid)
            {
                return "The image width is less than 900px";
            }
            else if (uploadResultEnum == UploadResultEnum.ImageHeightInvalid)
            {
                return "The image height is less than 600px";
            }
            else if (uploadResultEnum == UploadResultEnum.ImageTypeInvalid)
            {
                return "It is not valid image type";
            }
            else
            {
                return "No file has been selected";
            }
        }

        public static List<ErrorMessage> GetAllModelStateErrors(ModelStateDictionary modelState)
        {
            List<ErrorMessage> result = new List<ErrorMessage>();
            if (modelState == null || modelState.Count <= 0)
            {
                return result;
            }
           
            for (int i= 0; i<modelState.Values.Count; i++)
            {
                var value = modelState.Values.ElementAt(i);
                var key = modelState.Keys.ElementAt(i);

                string message = string.Empty;
                foreach (var error in value.Errors)
                {
                    if (!string.IsNullOrEmpty(error.ErrorMessage))
                    {
                        message = error.ErrorMessage;
                        break;
                    }
                }
                if (!string.IsNullOrEmpty(message))
                {
                    result.Add(new ErrorMessage { FieldName = key, Message = message });
                }
            }
            return result;
        }

        public static int GetJobStatusByFilterType(string filterType)
        {
            if (string.IsNullOrEmpty(filterType))
            {
                return -1;
            }
            else
            {
                filterType = filterType.ToLower();
                if (filterType == "active")
                {
                    return 1;
                }
                else if (filterType == "unpublished")
                {
                    return 0;
                }
                else if (filterType == "expired")
                {
                    return 2;
                }
                else
                {
                    return -1;
                }
            }
        }

        public static string GetBillingDescFromTransType(string transType)
        {
            if (string.IsNullOrEmpty(transType))
            {
                return string.Empty;
            }
            else
            {
                string temp = transType.ToLower().Trim();
                if (temp.Contains("job package"))
                {
                    int jobPackageID = Convert.ToInt32(temp[temp.Length - 1].ToString());
                    JobPackage package = GlobalUtilities.GetInstance().JobPackageList.Find(x => x.JobPackageID == jobPackageID);
                    if (package != null)
                    {
                        return package.Name + " Job Package";
                    }
                }
                return transType;
            }
        }

        public static List<string> ClearSearchTerm(string originalTerm)
        {
            List<string> result = new List<string>();
            if (string.IsNullOrEmpty(originalTerm)) return result;

            originalTerm = CommonUtilities.stripPunctuation(originalTerm);
            originalTerm = CommonUtilities.stripNoiseWords(originalTerm);

            if (!string.IsNullOrEmpty(originalTerm))
            {
                result = originalTerm.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToList();
                //trim -> remove empty entry -> remove duplicates
                result = result.Select(x => x.Trim()).Where(x => !string.IsNullOrEmpty(x)).Distinct().ToList();
            }
            return result;
        }

        public static List<string> SplitSearchTerm(string originalTerm, string delimiter)
        {
            List<string> result = new List<string>();
            if (string.IsNullOrEmpty(originalTerm)) return result;

            result = originalTerm.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries).ToList();
            //trim -> remove empty entry -> remove duplicates
            result = result.Select(x => x.Trim()).Where(x=>!string.IsNullOrEmpty(x)).Distinct().ToList();

            return result;
        }
    }
}